<template>
  <view class="user-center">
    <scroll-view class="scroll-area" scroll-y>
      <view class="bc-view" :style="{ paddingTop: 90 + headerHeight + 'rpx' }">
        <view class="flex-x-c header-col">
          <view class="flex-x-c">
            <view class="avator-border" @click="handleUploadAvatar">
              <u-avatar class="avator" size="55" :src="avatorImg"></u-avatar>
            </view>
            <view class="message">
              <view class="name" v-if="isLogin">{{ name }}</view>
              <view class="name" v-else @click="handleLogin">登录/注册</view>
              <view class="icon" v-if="isLogin">
                <u-tag :text="identifyingCName" size="mini" type="success"></u-tag>
              </view>
            </view>
          </view>
          <!-- <u-icon name="arrow-right" color="#fff" size="22"></u-icon> -->
        </view>
      </view>
      <u-popup
        border-radius="20"
        v-model="showExelTimePicker"
        mode="bottom"
        :mask="true"
        :zIndex="100"
      >
        <view style="padding: 40rpx; padding-bottom: calc(env(safe-area-inset-bottom) + 120rpx)">
          <text>年龄筛选（非必选）</text>
          <u--form labelPosition="left" :model="downloadParm" ref="uForm">
            <u-form-item
              label="开始日期"
              prop="startTime"
              labelWidth="180rpx"
              borderBottom
              @click="showStartTime = true"
            >
              <u--input
                v-model="downloadParm.startTime"
                disabled
                disabledColor="#ffffff"
                placeholder="请选择开始日期"
                border="none"
              ></u--input>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </u-form-item>
            <u-form-item
              label="结束日期"
              prop="endTime"
              labelWidth="180rpx"
              borderBottom
              @click="showEndTime = true"
            >
              <u--input
                v-model="downloadParm.endTime"
                disabled
                disabledColor="#ffffff"
                placeholder="请选择开始日期"
                border="none"
              ></u--input>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </u-form-item>
            <u-button type="success" text="下载" @click="onDateSelectorSubmit(2)"></u-button>
          </u--form>
        </view>
      </u-popup>
      <u-datetime-picker
        :show="showStartTime"
        v-model="parm.startTime"
        :minDate="Number(new Date('1968-01-01'))"
        :maxDate="maxDate"
        mode="date"
        @confirm="confirmStartTime"
        @cancel="showStartTime = false"
      ></u-datetime-picker>
      <u-datetime-picker
        :show="showEndTime"
        v-model="parm.endTime"
        mode="date"
        :minDate="minDate"
        :maxDate="Number(new Date())"
        @confirm="confirmEndTime"
        @cancel="showEndTime = false"
      ></u-datetime-picker>
      <view class="user-list">
        <view
          class="examine b-shadow b-w"
          v-if="identifying === 'admin' || identifying === 'enterprise'"
        >
          <view class="examine-title">
            {{ identifying === 'admin' ? '发布审核' : '我的发布' }}
          </view>
          <view class="flex-x-c ja">
            <view class="flex-y-c" @click="goPublishList(0)">
              <image class="inner-icon" src="@/static/order/all_order.png"></image>
              <view>全部</view>
            </view>
            <view class="flex-y-c" @click="goPublishList(1)">
              <image class="inner-icon" src="@/static/order/examine.png"></image>
              <view>待审核</view>
            </view>
            <view class="flex-y-c" @click="goPublishList(2)">
              <image class="inner-icon" src="@/static/order/exmaine_pass.png"></image>
              <view>通过</view>
            </view>
            <view class="flex-y-c" @click="goPublishList(3)">
              <image class="inner-icon" src="@/static/order/examine_no.png"></image>
              <view>拒绝</view>
            </view>
          </view>
        </view>
        <view
          class="flex-x-c pro-list"
          v-if="identifying === 'professional' || identifying === 'enterprise'"
        >
          <view class="pro-item flex-y-c b-shadow b-w" @click="handleBuild">
            <image class="pro-image" src="@/static/user/add_stand.png"></image>
            <view>建站</view>
          </view>
          <view class="pro-item flex-y-c b-shadow b-w" @click="handleResiger">
            <image class="pro-image id-ren" src="@/static/user/id_renzheng.png"></image>
            <view>身份认证</view>
            <view class="f20 fc-66">{{ applyId ? `(${auditName[audit]})` : '(未认证)' }}</view>
          </view>
        </view>
        <view class="flex-x-c pro-list" v-if="identifying === 'admin'">
          <view class="pro-item flex-y-c b-shadow b-w" @click="goStand">
            <image class="pro-image" src="@/static/user/add_stand.png"></image>
            <view>建站匹配</view>
          </view>
          <view class="pro-item flex-y-c b-shadow b-w" @click="goIdentityList">
            <image class="pro-image id-ren" src="@/static/user/id_renzheng.png"></image>
            <view>身份审核</view>
            <view class="f20 fc-66"></view>
          </view>
          <view class="pro-item flex-y-c b-shadow b-w" @click="handleExel">
            <image class="pro-image id-ren" src="@/static/public/user_list.png"></image>
            <view>人员名单</view>
            <view class="f20 fc-66"></view>
          </view>
        </view>
        <view class="flex-x-c pro-list" v-if="identifying === 'admin'">
          <view class="pro-item flex-y-c b-shadow b-w" @click="goUserList('professional')">
            <view>专家</view>
            <view class="sum-number">{{ userNumber.professionalNum }}</view>
          </view>
          <view class="pro-item flex-y-c b-shadow b-w" @click="goUserList('enterprise')">
            <view>企业</view>
            <view class="sum-number">{{ userNumber.enterpriseNum }}</view>
          </view>
          <view class="pro-item flex-y-c b-shadow b-w" @click="goUserList('manager')">
            <view>经理人</view>
            <view class="sum-number">{{ userNumber.managerNum }}</view>
          </view>
        </view>
        <view
          @click="handleResiger"
          class="pro-line-list b-shadow b-w flex-x-c"
          v-if="isLogin && (!identifying || identifying === 'manager')"
        >
          <image class="image-line" src="@/static/user/id_renzheng.png"></image>
          <view
            >身份认证<text style="margin-left: 10rpx" class="f20 fc-66">{{
              applyId ? `(${auditName[audit]})` : '(未认证)'
            }}</text>
          </view>
        </view>
        <!-- <view
          class="pro-line-list b-shadow b-w flex-x-c"
          v-if="identifying === 'professional' || identifying === 'manager'"
        >
          <image class="image-line" src="@/static/user/user_index.png"></image>
          <view>个人信息<text style="margin-left: 10rpx" class="f20 fc-66">(请补充)</text></view>
        </view> -->
        <!-- <view class="pro-line-list b-shadow b-w flex-x-c" v-if="identifying === 'enterprise'">
          <image class="image-line" src="@/static/user/business.png"></image>
          <view>企业信息<text style="margin-left: 10rpx" class="f20 fc-66">(请补充)</text></view>
        </view> -->
        <view
          class="pro-line-list b-shadow b-w flex-x-c"
          v-if="identifying === 'admin'"
          @click="goStandList"
        >
          <image class="image-line image_small" src="@/static/user/yixiang.png"></image>
          <view>建站意向</view>
        </view>
        <view
          @click="navPublish"
          class="pro-line-list b-shadow b-w flex-x-c"
          v-if="identifying === 'admin'"
        >
          <image class="image-line image_small" src="@/static/user/notice.png"></image>
          <view>发布通知</view>
        </view>
        <view class="pro-line-list b-shadow b-w flex-x-c" @click="downloadWord">
          <image class="image-line image_small" src="@/static/user/form_img.png"></image>
          <view>博士站申请表单下载</view>
        </view>
        <view
          @click="makePhoneCall"
          class="pro-line-list b-shadow b-w flex-x-c"
          v-if="identifying !== 'admin'"
        >
          <image class="image-line image_small" src="@/static/user/call_manager.png"></image>
          <view>
            <view>联系客服</view>
            <view class="fc-66" style="font-size: 22rpx; margin-top: 10rpx"
              >上班时间(9:00-17:00)</view
            >
          </view>
        </view>
        <view
          class="pro-line-list b-shadow b-w flex-x-c out-login"
          v-if="identifying === 'admin' || identifying === 'dept'"
          @click="handleShowPswd"
        >
          <image class="image-line image_small" src="@/static/user/password.png"></image>
          <view>修改密码</view>
        </view>
        <view
          class="pro-line-list b-shadow b-w flex-x-c out-login"
          v-if="isLogin"
          @click="loginOut"
        >
          <image class="image-line" src="@/static/user/ic_home_out.png"></image>
          <view>退出登录</view>
        </view>
      </view>
    </scroll-view>
    <public-confirm
      ref="confirm"
      message="是否退出登录"
      :confShow="loginOutConfShow"
      @confirm="handleLoginOut"
      @cancel="cancel"
    ></public-confirm>
    <public-confirm
      ref="confirm"
      message="您还未认证身份,无法建站"
      :confShow="noAuthority"
      @confirm="handleNoAuthority"
      @cancel="cancel"
    ></public-confirm>
    <shop-footer ref="vShopFooter" currentUrl="/pages/user/index"></shop-footer>
    <u-action-sheet
      :show="showRole"
      :actions="actions"
      title="请选择角色类型"
      @close="closeRole"
      @select="sexSelect"
    >
    </u-action-sheet>
    <u-action-sheet
      :show="showExelType"
      :actions="downTypeList"
      title="请选择下载角色类型"
      @close="closeRole"
      @select="selectExelList"
    >
    </u-action-sheet>
  </view>
</template>

<script>
import shopFooter from '@/common/public/shop_footer'
import myDateTimePicker from '@/components/dengrq-datetime-picker/dateSelector/index.vue'
import uPopup from '@/common/uView/u-popup'
import UpLoadImg from '@/ext/upLoadImg.js'
const auditName = {
  0: '待审核',
  1: '已认证',
  2: '未通过',
}

export default {
  components: {
    shopFooter,
    myDateTimePicker,
    uPopup,
  },
  data() {
    return {
      isLogin: !!this.$globalData.state.token,
      auditName,
      startDate: '1980-01-01',
      mode: 1,
      noAuthority: false,
      showRole: false,
      actions: [
        {
          name: '专家',
        },
        {
          name: '女',
        },
        {
          name: '保密',
        },
      ],
      showExelType: false,
      showExelTimePicker: false,
      loginOutConfShow: false,
      headerHeight: this.$globalData.state.headerHeight,
      name: '',
      // identifying: '',
      identifyingCName: '',
      userNumber: {
        managerNum: 0,
        enterpriseNum: 0,
        professionalNum: 0,
      },
      showStartTime: false,
      showEndTime: false,
      minDate: Number(new Date('1968-01-01')),
      maxDate: Number(new Date()),
      parm: {
        startTime: '',
        endTime: '',
      },
      downloadParm: {
        startTime: '',
        endTime: '',
      },
      downTypeList: [
        {
          id: 1,
          name: '创新站名单',
        },
        {
          id: 2,
          name: '青年专家名单',
        },
        {
          id: 3,
          name: '企业技术需求',
        },
        {
          id: 4,
          name: '经理人名单',
        },
      ],
      applyId: null,
      audit: null,
    }
  },
  computed: {
    userInfoDetail() {
      return this.$globalData.state.userInfoDetail
    },
    avatorImg() {
      return this.userInfoDetail.avatar
    },
  },
  watch: {
    userInfoDetail: {
      handler(newVal) {
        if (newVal) {
          // this.identifying = newVal.identifying
          this.identifyingCName = this.$utils.identifyingCName(newVal.identifying)
          if (newVal.identifying === 'admin' || newVal.identifying === 'dept') {
            this.name = newVal.account
          } else if (newVal.identifying === 'professional') {
            this.name = newVal.professionalApplyVo.name
          } else if (newVal.identifying === 'enterprise') {
            this.name = newVal.enterpriseApplyVo.enterpriseName
          } else if (newVal.identifying === 'manager') {
            this.name = newVal.managerApplyVo.name
          } else {
            this.name = newVal.mobile
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },
  onLoad(e) {
    this.isLogin && this.queryRoleList()
  },
  onShow() {
    this.upLoad = new UpLoadImg()
    this.isLogin && this.getUserInfo()
    this.isLogin && this.queryExaimineStatus()
  },
  methods: {
    getUserInfo() {
      this.$request(`/user/loginUser`, {}).then((res) => {
        let info = res.result
        if (info.identifying == 'admin') this.queryUserNumber()
        this.$globalData.commit('setLoginInfo', {
          userInfoDetail: {
            userId: info.id,
            mobile: info.mobile,
            avatar: info.avatar,
            account: info.account, //管理员、部门账号
            identifying: info.identifying, //身份类型：管理员-admin，部门-dept，专家-professional，企业-enterprise，经理人-manager
            professionalApplyVo: info.professionalApplyVo, //专家信息
            enterpriseApplyVo: info.enterpriseApplyVo, //企业信息
            managerApplyVo: info.managerApplyVo, //经理人信息
          },
        })
      })
    },
    // 获取登录用户信息
    queryExaimineStatus() {
      this.$request(`/roleApply/myRoleApplyPage`, { pageNo: 1, pageSize: 5 }).then((res) => {
        const records = res.result.records
        if (!records || !records.length) return
        const lastReord = records[0]
        this.audit = lastReord.audit
        this.applyId = lastReord.id
        this.roleId = lastReord.roleId
      })
    },
    handleResiger() {
      // 提交身份审核
      if (this.applyId) {
        let url = `/pages/form/manager`
        if (this.roleId == 4) {
          url = `/pages/form/company`
        } else if (this.roleId == 3) {
          url = `/pages/form/workerForm`
        }
        url += `?examineId=${this.applyId}&myself=1`
        this.$routeUtils.navigateTo({ url })
      } else {
        this.showRole = true
      }
    },
    // navDetail() {
    //   let url = `/pages/form/manager`
    //   if (this.identifying === 'enterprise') {
    //     url = `/pages/form/company`
    //   } else if (this.identifying === 'professional') {
    //     url = `/pages/form/workerForm`
    //   }
    //   url += `?examineId=${this.userInfoDetail.userId}&myself=1`
    //   this.$routeUtils.navigateTo({ url })
    // },
    handleExel() {
      this.showExelType = true
    },
    downloadWord() {
      this.downloadFile()
    },
    selectExelList(param) {
      if (param.id === 2) {
        this.parm = {
          startTime: '',
          endTime: '',
        }
        this.downloadParm = {
          startTime: '',
          endTime: '',
        }
        this.showExelTimePicker = true
      } else {
        this.onDateSelectorSubmit(param.id)
      }
      // this.downloadFile('http://8.138.110.118:80/excel/exportProfessionalExcel')
    },
    onDateSelectorSubmit(type) {
      this.showExelTimePicker = false
      const urlList = [
        '/excel/exportTalentMatchExcel',
        '/excel/exportProfessionalExcel',
        '/excel/exportEnterprisePublishExcel',
        '/excel/exportManagerlExcel',
      ]
      const urlName = ['创新站名单', '青年专家名单', '企业技术需求名单', '科技经理人名单']
      const exelName = urlName[type - 1]
      this.$request(
        urlList[type - 1],
        type === 2 ? this.downloadParm : {},
        'api',
        false,
        null,
        false,
        'arraybuffer',
      ).then((res) => {
        const filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}${exelName}.xlsx`
        const fs = uni.getFileSystemManager()
        fs.writeFile({
          filePath: filePath,
          data: res,
          encoding: 'binary',
          success: function (red) {
            // that.isShowProgress = false;
            uni.showModal({
              title: '提示',
              content: '文件已保存：' + filePath,
              cancelText: '我知道了',
              confirmText: '打开文件',
              success: function (res) {
                if (res.confirm) {
                  uni.openDocument({
                    filePath: filePath,
                    showMenu: true,
                    success: (sus) => {
                      console.log('成功打开')
                    },
                  })
                }
              },
            })
          },
          fail: (err) => {
            console.log(err)
          },
        })
      })
    },
    downloadFile(url) {
      const downloadTask = uni.downloadFile({
        url: 'https://www.oss.talentmatch.top/talent/word/%E7%9C%81%E2%80%9C%E7%A7%91%E5%88%9B%E4%B8%AD%E5%9B%BD%E2%80%9D%E5%8D%9A%E5%A3%AB%E5%88%9B%E6%96%B0%E7%AB%99%E5%BB%BA%E8%AE%BE%E8%AF%95%E7%82%B9%E9%80%9A%E7%9F%A5%EF%BC%88%E7%AE%80%E7%89%88%EF%BC%89.doc',
        success: (res) => {
          if (res.statusCode === 200) {
            // this.isShowProgress = false;
            console.log('下载成功')
          }
          let that = this
          const filePath = `${wx.env.USER_DATA_PATH}/省“科创中国”博士创新站建设试点通知（简版）.doc`
          const fs = uni.getFileSystemManager()
          fs.saveFile({
            tempFilePath: res.tempFilePath,
            filePath: filePath,
            success: function (red) {
              // that.isShowProgress = false;
              uni.showModal({
                title: '提示',
                content: '文件已保存：' + red.savedFilePath,
                cancelText: '我知道了',
                confirmText: '打开文件',
                success: function (res) {
                  if (res.confirm) {
                    uni.openDocument({
                      filePath: red.savedFilePath,
                      showMenu: true,
                      success: (sus) => {
                        console.log('成功打开')
                      },
                    })
                  }
                },
              })
            },
          })
        },
      })
    },
    queryUserNumber() {
      this.$request(`/user/statisticsUserTypeNum`, {}).then((res) => {
        Object.assign(this.userNumber, res.result)
      })
    },
    handleBuild() {
      if (this.identifyingCName == '游客') {
        this.noAuthority = true
        return
      }
      this.$routeUtils.navigateTo({
        url: '/pages/stand/build',
      })
    },
    navPublish() {
      this.$routeUtils.navigateTo({
        url: '/pages/user/publishNotice',
      })
    },
    queryRoleList() {
      this.$request('/role/getRoleList', {}).then((res) => {
        this.actions = res.result || []
      })
    },
    cancel() {
      this.loginOutConfShow = false
    },
    handleLogin() {
      this.$routeUtils.navigateTo({
        url: '/pages/user/login',
      })
    },
    handleLoginOut() {
      // this.$socket.closeSocket()
      this.$globalData.commit('clearLoginInfo')
      this.$routeUtils.reLaunch({
        url: '/pages/index/index',
      })
    },
    handleNoAuthority() {
      this.handleResiger()
    },
    handleShowPswd() {
      this.$routeUtils.navigateTo({
        url: '/pages/user/password',
      })
    },
    loginOut() {
      this.loginOutConfShow = true
    },
    closeRole() {
      this.showRole = false
      this.showExelType = false
    },
    sexSelect(param) {
      if (param.id == 4) {
        this.$routeUtils.navigateTo({
          url: '/pages/form/company?id=4&isAdd=1',
        })
      } else if (param.id == 3) {
        this.$routeUtils.navigateTo({
          url: '/pages/form/workerForm?id=3&isAdd=1',
        })
      } else if (param.id == 5) {
        this.$routeUtils.navigateTo({
          url: '/pages/form/manager?id=5&isAdd=1',
        })
      }
    },

    goIdentityList() {
      this.$routeUtils.navigateTo({
        url: '/pages/user/identityList?status=-1',
      })
    },
    goStand() {
      this.$routeUtils.navigateTo({
        url: '/pages/stand/meta',
      })
    },
    goStandList() {
      this.$routeUtils.navigateTo({
        url: '/pages/stand/intention',
      })
    },
    goPublishList(type) {
      this.$routeUtils.navigateTo({
        url: '/pages/user/myPublish?type=' + type,
      })
    },
    goUserList(type) {
      this.$routeUtils.navigateTo({
        url: '/pages/user/list?type=' + type,
      })
    },
    confirmStartTime(e) {
      this.showStartTime = false
      this.downloadParm.startTime = this.$utils.dateFormat(new Date(e.value), 'YYYY-mm-dd')
      this.minDate = e.value
    },
    checkIfAllImages(files) {
      const imageExtensions = ['jpg', 'jpeg', 'png', 'gif']
      return files.every((file) => {
        const fileName = file.name || file.path
        const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
        return imageExtensions.includes(fileExtension)
      })
    },
    handleUploadAvatar() {
      this.isLogin &&
        this.upLoad.getOssToken().then((res) => {
          this.$request('/user/modifyUserAvatar', {
            avatar: res.fileName,
          }).then((res) => {
            this.$utils.toast('上传图片成功！')
            this.getUserInfo()
          })
        })
    },
    makePhoneCall() {
      uni.makePhoneCall({
        phoneNumber: '0591-88019193',
      })
    },
    confirmEndTime(e) {
      this.showEndTime = false
      this.downloadParm.endTime = this.$utils.dateFormat(new Date(e.value), 'YYYY-mm-dd')
      this.maxDate = e.value
    },
  },
}
</script>

<style lang="scss" scoped>
.user-center {
  background: #f6f6f6;
  overflow: hidden;
  height: 100vh;
  position: relative;
}
.bc-view {
  background-color: $uni-color-primary;
  border-bottom-left-radius: 30rpx;
  border-bottom-right-radius: 30rpx;
  width: 750rpx;
  padding: 90rpx 40rpx 130rpx 40rpx;
}
.user-list {
  margin-top: -60rpx;
  padding: 0 40rpx 100rpx;
  .examine {
    padding: 30rpx 0;
    border-radius: 10rpx;
    .examine-title {
      padding: 0 40rpx 20rpx;
    }
    .inner-icon {
      width: 40rpx;
      height: 40rpx;
      margin-bottom: 10rpx;
    }
  }
  .out-login {
    // margin-bottom: calc(170rpx + env(safe-area-inset-bottom));
  }
}
.pro-list {
  margin-top: 30rpx;
  .pro-item {
    width: 345rpx;
    height: 150rpx;
    margin-right: 30rpx;
    justify-content: center;
    border-radius: 10rpx;
    .pro-image {
      width: 50rpx;
      height: 50rpx;
      margin-bottom: 20rpx;
    }
    .id-ren {
      width: 70rpx;
      height: 70rpx;
      margin-bottom: 0rpx;
    }
  }
  .pro-item:last-child {
    margin-right: 0rpx;
  }
}
.pro-line-list {
  margin-top: 30rpx;
  height: 150rpx;
  padding-left: 30rpx;
  border-radius: 10rpx;
}
.image-line {
  width: 60rpx;
  height: 60rpx;
  margin-right: 20rpx;
}
.image_small {
  margin-left: 10rpx;
  width: 40rpx;
  height: 40rpx;
  margin-right: 28rpx;
}
.header-col {
  justify-content: space-between;
  .avator-border {
    border-radius: 50%;
    border: 4rpx solid #fff;
  }
  .message {
    margin-left: 20rpx;
    .name {
      color: #fff;
      font-size: 32rpx;
    }
    .icon {
      display: inline-flex;
      margin-top: 20rpx;
    }
  }
}

.scroll-area {
  flex: 1;
  height: 100%;
}

.sum-number {
  color: #3c9cff;
  margin-top: 10rpx;
}
</style>
